<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Queries\ActivityQuery;
use App\Http\Resources\ActivityResource;
use App\Http\Resources\UserDrawResource;
use App\Models\UserDraw;

class ActivityController extends Controller
{
    public function index(ActivityQuery $query)
    {
        $rows = $query->where('show', true)->paginate(5);
        return $this->resource(ActivityResource::collection($rows));
    }

    public function show($id, ActivityQuery $query, Request $request)
    {
        $activity = $query->where('id', $id)->with(['vehicles', 'vehicles.series'])->firstOrFail();
        $user = $request->user();
        $activity->is_join = UserDraw::where('activity_id', $activity->id)->where('user_id', $user->id)->exists();
        $vehicles = $activity->vehicles->toArray();
        $series = [];
        foreach ($vehicles as $vehicle) {
            $series[$vehicle['vehicle_series_id']] = $vehicle['series'];
        }
        $activity->series = $series;
        return $this->resource(new ActivityResource($activity));
    }

    public function draw($id, ActivityQuery $query, Request $request)
    {
        $activity = $query->where('id', $id)->firstOrFail();
        $user = $request->user();
        $recond = app('ActivityService')->draw($activity, $user);
        return $this->resource(new UserDrawResource($recond));
    }
}
